<template>
  <el-dialog
    :visible.sync="visible"
    title="设置相差金额"
    width="1200px"
    :before-close="handleClose"

  >

    <el-tabs v-model="activeTab"  type="border-card" >
      <el-tab-pane :name="1" label="添加相差金额">
        <el-form :model="formData"  :rules="rules" ref="formRef" label-width="100px" style="padding: 20px 40px">
          <el-form-item  :label="$t('请选择门店')" prop="shopId">
            <el-select v-model="formData.shopId" clearable class="filter-item" :placeholder="$t('请选择门店')" @change="onShopChange">
              <el-option v-for="item in shops" :value="item.id" :label="item.name">{{item.name}}</el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="员工名称" prop="adminId">
            <el-select
              v-model="formData.adminId"
              clearable
              class="filter-item"
              :placeholder="$t('请选择员工')"
              @change="onAdminChange"
            >
              <el-option
                v-for="item in admins"
                :value="item.id"
                :label="item.nickName"
              >
                {{ item.nickName }}
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input disabled v-model="formData.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>

          <el-form-item label="差异数值" prop="amount">
            <el-input-number v-model="formData.amount" :min="0" :precision="2" placeholder="请输入金额" />
          </el-form-item>

          <el-form-item label="启用状态" prop="enabled">
            <el-switch
              v-model="formData.enabled"
              :active-value="true"
              :inactive-value="false"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-form>
        <div style="display: flex; justify-content: flex-end; margin-top: 20px; padding-right: 40px">
          <el-button @click="handleClose">取 消</el-button>
          <el-button v-show="formData.id" @click="resetFormData" type="warning">取消编辑</el-button>
          <el-button type="primary" @click="handleConfirm">
            {{ formData.id ? '提交编辑' : '确 定' }}
          </el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane :name="2" label="列表">
        <!-- 🔍 搜索按钮区域 -->
        <div style="padding: 20px; display: flex; justify-content: flex-start; gap: 12px">
          <el-button type="success" icon="el-icon-check" @click="handleBatchEnable" style="margin-right: 10px">
            批量启用
          </el-button>
          <el-button type="warning" icon="el-icon-close" @click="handleBatchDisable" style="margin-right: 10px">
            批量禁用
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete" style="margin-right: 20px">
            批量删除
          </el-button>
          <el-select filterable v-model="queryParams.shopId" clearable class="filter-item" :placeholder="$t('请选择门店')">
            <el-option v-for="item in shops" :value="item.id" :label="item.name"></el-option>
          </el-select>
          <el-select filterable v-model="queryParams.adminId" clearable class="filter-item" :placeholder="$t('请选择员工')">
            <el-option v-for="item in adminOptions" :value="item.id" :label="item.nickName"></el-option>
          </el-select>
          <el-select
            v-model="queryParams.enabled"
            :placeholder="$t('请选择状态')"
            clearable
          >
            <el-option :label="$t('启用')" :value="1"></el-option>
            <el-option :label="$t('停用')" :value="0"></el-option>
          </el-select>
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="——"
            :start-placeholder='$t("开始日期")'
            :end-placeholder='$t("结束日期")'
            :picker-options="{
              shortcuts: [
                {
                  text: '最近一周',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    picker.$emit('pick', [start, end]);
                  }
                },
                {
                  text: '最近一个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setMonth(start.getMonth() - 1);
                    picker.$emit('pick', [start, end]);
                  }
                },
                {
                  text: '最近三个月',
                  onClick(picker) {
                    const end = new Date();
                    const start = new Date();
                    start.setMonth(start.getMonth() - 3);
                    picker.$emit('pick', [start, end]);
                  }
                }
              ]
            }"
          >
          </el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="getList"
          >
            {{ $t('Search') }}
          </el-button>
        </div>
        <div >
        <el-table
          ref="tableRef"
          v-loading="loading" :data="list" :element-loading-text="$t('Searching')"
          max-height="400"
          :header-cell-style="{ background: '#f3f6fd', color: '#555' }"

          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column align="center" fixed type="index" :label="$t('排序')" width="50"></el-table-column>
          <el-table-column label="门店名称" prop="shopName"  align="center" width="240"></el-table-column>
          <el-table-column label="用户昵称" prop="nickname" align="center" width="180"></el-table-column>
          <el-table-column label="邮箱" prop="email" align="center" width="180"></el-table-column>
          <el-table-column label="相差金额" align="center" prop="amount" width="180">
            <template slot-scope="scope">
              {{ NumberUtils.formatFixed2(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column align="center" property="addTime" label="创建时间" width="200">
            <template slot-scope="scope">
              <i class="el-icon-time">{{ scope.row.addTime }}</i>
            </template>
          </el-table-column>
          <el-table-column label="启用状态" prop="enabled" align="center" width="180">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.enabled"
                :active-value="true"
                :inactive-value="false"
                active-text="启用"
                inactive-text="禁用"
                @change="onEnableChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column align="center" :label="$t('Operate')" width="120" fixed="right" class-name="small-padding fixed-width">
            <template slot="header" slot-scope="{ row }">
              <i class="el-icon-setting"></i>
              {{ $t('Operate') }}
            </template>
            <template slot-scope="scope">
              <el-link type="primary" @click="handleEdit(scope.row)">编辑</el-link>
              <el-link type="danger" @click="handleDeleted(scope.row)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="!loading"
          :total="queryParams.total"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.limit"
          @pagination="getList"
        />
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script>
import amountDifferenceApi from '@/api/cashSettlement'
import { allForPerm } from '@/api/shop'
import adminApi from '@/api/admin'
import NumberUtils from "@/utils/numberUtils";
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
export default {
  name: 'AmountDifferenceDialog',
  components: {
    Pagination,
  },
  data() {
    return {
      amountDifferenceApi,
      adminApi,
      NumberUtils,
      activeTab:2,
      visible: false,
      list: [], // 可从接口加载
      loading: false,
      formData: {
        id: null,
        shopId: null,
        adminId: null,
        amount: 0,
        email: '',
        enabled: true
      },
      shops: [], //所有门店信息
      admins:[],
      adminOptions:[],
      rules: {
        shopId: [
          { required: true, message: '门店ID不能为空', trigger: 'blur' },
          { type: 'number', min: 1, message: '门店ID必须是正整数', trigger: 'blur' }
        ],
        adminId: [
          { required: true, message: '用户ID必须是正整数', trigger: 'blur' },
          { type: 'number', min: 1, message: '用户ID必须是正整数', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '金额不能小于0', trigger: 'blur' },
          { type: 'number', min: 0, message: '金额不能小于0', trigger: 'blur' }
        ],
        enabled: [
          { required: true, message: '启用状态不能为空', trigger: 'change' }
        ]
      },
      queryParams: {
        shopId: undefined,
        adminId: undefined,
        enabled: undefined,
        createTime: [],
        page: 1,
        limit: 10,
        total:0,
      },
      selectedRows: [],
    }
  },
  methods: {
    NumberUtils() {
      return NumberUtils
    },
    open() {
      this.visible = true
      this.getInit()
    },
    handleClose() {
      this.visible = false
    },
    handleConfirm() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return

        const isEdit = !!this.formData.id
        const api = isEdit ? this.amountDifferenceApi.edit : this.amountDifferenceApi.add
        const successMsg = isEdit ? '编辑成功' : '添加成功'

        api(this.formData).then(() => {
          this.$message.success(successMsg)
          this.getList()
          this.resetFormData()
          this.activeTab = 2
        })
      })
    },
    getList() {
      this.loading = true
      this.amountDifferenceApi.page(this.queryParams).then(res => {
        this.list = res.data.data.list || []
        this.queryParams.total = res.data.data.total
      }).finally(() => {
        this.loading = false
      })
    },

    getInit() {
      this.getList()
      allForPerm().then((response) => {
        this.shops = response.data.data.list;
      })
      this.adminApi.simpleList({ shopId: undefined }).then((res) => {
        this.adminOptions = res.data.data || [];
      })
    },
    onShopChange() {
      this.getSimpleList(this.formData.shopId)
      this.formData.adminId = undefined
    },
    getSimpleList(shopId) {
      this.adminApi.simpleList({ shopId: shopId }).then((res) => {
        this.admins = res.data.data || [];
      })
    },
    onEnableChange(row) {
      const payload = {
        ids: [row.id],           // 后端接口通常需要 id 数组
        enabled: row.enabled        // 当前状态（true/false）
      }

      this.amountDifferenceApi.enableBatch(payload).then(() => {
        this.$message.success(`已${row.enabled ? '启用' : '禁用'}成功`)
        //this.getList() // 可选：刷新列表，确保数据一致
      }).catch(() => {
        this.$message.error('操作失败')
        row.enabled = !row.enabled // 回滚状态
      })
    },
    onAdminChange(adminId) {
      const selected = this.admins.find(item => item.id === adminId)
      this.formData.email = selected ? selected.email : ''
    },
    handleEdit(row) {
      // 赋值当前行数据到表单
      this.formData = {
        id: row.id,
        shopId: row.shopId,
        adminId: row.adminId,
        amount: row.amount,
        email: row.email,
        enabled: row.enabled
      }
      this.admins = []
      this.getSimpleList(this.formData.shopId)
      // 切换到“添加相差金额”标签页
      this.activeTab = 1
    },
    handleDeleted(row) {
      this.$confirm('确定要删除该记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const payload = { ids: [row.id] }
        this.amountDifferenceApi.deletedBatch(payload).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        // 用户点击取消，不做任何处理
      })
    },
    resetFormData() {
      this.formData = {
        id: null,
        shopId: null,
        adminId: null,
        amount: 0,
        email: '',
        enabled: true
      }
    },
    handleSelectionChange(val) {
      this.selectedRows = val
    },
    handleBatchEnable() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要启用的记录')
        return
      }
      const ids = this.selectedRows.map(item => item.id)
      this.amountDifferenceApi.enableBatch({ ids, enabled: true }).then(() => {
        this.$message.success('批量启用成功')
        this.getList()
      }).catch(() => {
        this.$message.error('批量启用失败')
      })
    },
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的记录')
        return
      }
      this.$confirm('确定要批量删除所选记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedRows.map(item => item.id)
        this.amountDifferenceApi.deletedBatch({ ids }).then(() => {
          this.$message.success('批量删除成功')
          this.getList()
        }).catch(() => {
          this.$message.error('批量删除失败')
        })
      })
    },
    handleBatchDisable() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要禁用的记录')
        return
      }
      const ids = this.selectedRows.map(item => item.id)
      this.amountDifferenceApi.enableBatch({ ids, enabled: false }).then(() => {
        this.$message.success('批量禁用成功')
        this.getList()
      }).catch(() => {
        this.$message.error('批量禁用失败')
      })
    },
  }
}
</script>
